/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pua.uniandes.servicios;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.PostActivate;
import javax.ejb.Stateless;

/**
 *
 * @author jd.velasquez3209
 */
@Stateless
public class TransmisionVideoBean implements TransmisionVideoBeanRemote, TransmisionVideoBeanLocal {

    private DatagramSocket ds;

    @Override
    public void guardarPaqueteVideo(ArrayList<byte[]> paqueteVideo, int numeroPaquete) {


        
        try {


            File f = new File("video" + numeroPaquete + ".txt");
            


            if (!f.exists()) {
                f.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(f);


            for (int i = 0; i < paqueteVideo.size(); i++) {
                byte[] bs = paqueteVideo.get(i);
                fos.write(bs, 0, bs.length);
            }
            fos.close();




        } catch (FileNotFoundException ex) {
            Logger.getLogger(TransmisionVideoBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TransmisionVideoBean.class.getName()).log(Level.SEVERE, null, ex);
        }



    }

    @PostActivate
    public void inicializar() throws SocketException {



        ds = new DatagramSocket();

        ds.setBroadcast(true);




    }

    private void enviarPaqueteVideo(File f) {


        try {


       
            byte[] buf = new byte[1024];
            FileInputStream in = new FileInputStream(f);
            int i = 0;
            int bytecount = 1024;
            while ((i = in.read(buf, 0, 1024)) != -1) {

                bytecount = bytecount + 1024;
                ds.send(new DatagramPacket(buf, i, InetAddress.getByName("127.0.0.255"), 2345));


            }
        } catch (IOException ex) {
            Logger.getLogger(TransmisionVideoBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void iniciarTransmicionVideo(int cantidadPartesVideo) {



        for (int i = 0; i < cantidadPartesVideo; i++) {
            File f = new File("video" + i + ".txt");
            enviarPaqueteVideo(f);

        }



    }
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
}
